
$(function() {
	var logTable = reRunModel.initTable();
	// init date tables
	var jobTable = $("#procedure_list").dataTable({
		"deferRender": true,
		"processing" : true,
	    "serverSide": true,
		"ajax": {
			url: base_url + "/procedure/pageList",
			type:"post",
	        data : function ( d ) {
	        	var obj = {};
	        	obj.OBJECT_NAME = $('#OBJECT_NAME').val();
                obj.PROCEDURE_NAME = $('#PROCEDURE_NAME').val();
	        	obj.IS_HISTORY = $('#IS_HISTORY').val();
	        	obj.start = d.start ;
	        	obj.length = d.length ;
                return obj;
            }
	    },
	    "searching": false,
	    "ordering": false,
	    //"scrollX": true,	// X轴滚动条，取消自适应
	    "columns": [
	                {

	                	"data": 'OBJECT_ID',
						"bSortable": false,
						"visible" : true,
						"width":'8%'
					},
	                {

						"data": 'OBJECT_NAME',
	                	"visible" : true,
						"width":'20%',
                        //"render": function ( data, type, row ) {
	            		//	var groupMenu = $("#jobGroup").find("option");
	            		//	for ( var index in $("#jobGroup").find("option")) {
	            		//		if ($(groupMenu[index]).attr('value') == data) {
							//		return $(groupMenu[index]).html();
							//	}
							//}
	            		//	return data;
	            		//}
            		},
	                {

	                	"data": 'OBJECT_DESC',
						"visible" : true,
						"width":'20%'
					},
					{

						"data": 'PROCEDURE_NAME',
						"width":'20%',
						//"visible" : true,
						//"render": function ( data, type, row ) {
						//	if ('GLUE_GROOVY'==row.glueType) {
						//		return "GLUE模式(Java)";
						//	} else if ('GLUE_SHELL'==row.glueType) {
						//		return "GLUE模式(Shell)";
						//	} else if ('GLUE_PYTHON'==row.glueType) {
						//		return "GLUE模式(Python)";
						//	}else if  ('GLUE_NODEJS'==row.glueType){
						//		return "GLUE模式(Nodejs)";
						//	} else if ('BEAN'==row.glueType) {
						//		return "BEAN模式：" + row.executorHandler;
						//	}
						//	return row.executorHandler;
						//}
					},
	                {

						"data": 'RUNTIME', "visible" : true,
						"width":'10%',},

	                {

						"data": 'HIS_RUN_TIME',
	                	"visible" : true,
						"width":'10%',
	                	//"render": function ( data, type, row ) {
	                	//	return data?moment(new Date(data)).format("YYYY-MM-DD HH:mm:ss"):"";
	                	//}
	                },
	                {
						"data": '操作',
						"width":'15%',
	                	"render": function ( data, type, row ) {
	                		return function(){
	                			// status
	                			var pause_resume = "";
	                			if ('Y' == row.ACTIVE) {
	                				pause_resume = '<button class="btn btn-primary btn-xs job_operate" _type="job_pause" type="button">暂停</button>  ';
								} else if ('N' == row.ACTIVE){
									pause_resume = '<button class="btn btn-primary btn-xs job_operate" _type="job_resume" type="button">恢复</button>  ';
								}
	                			// log url
	                			var logUrl =base_url+  '/procedure/indexLog?PROCEDURE_NAME='+ row.PROCEDURE_NAME;

	                			// log url
	                			var codeBtn = "";
                                //if ('BEAN' != row.glueType) {
									//var codeUrl = base_url +'/jobcode?jobId='+ row.OBJECT_ID;
									//codeBtn = '<button class="btn btn-warning btn-xs" type="button" onclick="javascript:window.open(\'' + codeUrl + '\')" >GLUE</button>  '
                                //}

								// html
                                tableData['key'+row.OBJECT_ID] = row;
								var html = '<p id="'+ row.OBJECT_ID +'" >'+
									pause_resume +
									'<button class="btn btn-primary btn-xs logUrl" _type="job_log" type="button" onclick="logUrl(\''+logUrl+'\')"  _url="'+logUrl+'" >日志</button> <br> '+
									'<button class="btn btn-warning btn-xs update" _type="job_edit"  type="button">编辑</button>  '+
									codeBtn +
									'<button class="btn btn-danger btn-xs job_operate" _type="job_del" type="button">删除</button>  '+
									'</p>';

	                			return html;
							};
	                	}
	                }
	            ],
		"language" : {
			"sProcessing" : "处理中...",
			"sLengthMenu" : "每页 _MENU_ 条记录",
			"sZeroRecords" : "没有匹配结果",
			"sInfo" : "第 _PAGE_ 页 ( 总共 _PAGES_ 页，_TOTAL_ 条记录 )",
			"sInfoEmpty" : "无记录",
			"sInfoFiltered" : "(由 _MAX_ 项结果过滤)",
			"sInfoPostFix" : "",
			"sSearch" : "搜索:",
			"sUrl" : "",
			"sEmptyTable" : "表中数据为空",
			"sLoadingRecords" : "载入中...",
			"sInfoThousands" : ",",
			"oPaginate" : {
				"sFirst" : "首页",
				"sPrevious" : "上页",
				"sNext" : "下页",
				"sLast" : "末页"
			},
			"oAria" : {
				"sSortAscending" : ": 以升序排列此列",
				"sSortDescending" : ": 以降序排列此列"
			}
		}
	});

    // table data
    var tableData = {};

	// 搜索按钮
	$('#searchBtn').on('click', function(){
		jobTable.fnDraw();
	});

	// jobGroup change
	$('#jobGroup').on('change', function(){
        //reload
        var jobGroup = $('#jobGroup').val();
        window.location.href = base_url + "/jobinfo?jobGroup=" + jobGroup;
    });

	// job operate
	$("#procedure_list").on('click', '.job_operate',function() {
		var typeName;
		var url;
		var needFresh = false;

		var type = $(this).attr("_type");

		if ("job_pause" == type) {
			typeName = "暂停";
			url = base_url + "/procedure/changeActive?ACTIVE=N";
			needFresh = true;
		} else if ("job_resume" == type) {
			typeName = "恢复";
			url = base_url + "/procedure/changeActive?ACTIVE=Y";
			needFresh = true;
		}
		//else if ("job_edit" == type) {
		//	typeName = "编辑";
		//	url = base_url + "/procedure/getIndex";
		//	needFresh = true;
		//}
		else if ("job_del" == type) {
			typeName = "删除";
			url = base_url + "/procedure/delete";
			needFresh = true;
		} else {
			return;
		}

		var id = $(this).parent('p').attr("id");

		layer.confirm('确认' + typeName + '?', {icon: 3, title:'系统提示'}, function(index){
			layer.close(index);

			$.ajax({
				type : 'POST',
				url : url,
				data : {
					"OBJECT_ID" : id
				},
				dataType : "json",
				success : function(data){
					if (data.code == 200) {

						layer.open({
							title: '系统提示',
							content: typeName + "成功",
							icon: '1',
							end: function(layero, index){
								if (needFresh) {
									//window.location.reload();
									jobTable.fnDraw();
								}
							}
						});
					} else {
						layer.open({
							title: '系统提示',
							content: (data.msg || typeName + "失败"),
							icon: '2'
						});
					}
				},
			});
		});
	});

	// jquery.validate 自定义校验 “英文字母开头，只含有英文字母、数字和下划线”
	jQuery.validator.addMethod("myValid01", function(value, element) {
		var length = value.length;
		var valid = /^[a-zA-Z][a-zA-Z0-9_]*$/;
		return this.optional(element) || valid.test(value);
	}, "只支持英文字母开头，只含有英文字母、数字和下划线");

	// 新增
	$(".add").click(function(){
		$('#addModal').modal({backdrop: false, keyboard: false}).modal('show');

	});

	$('#addModal,#updateModal').find('input[dateFlag="Y"]').daterangepicker({
			singleDatePicker: true,
			showDropdowns: true,
			autoApply:true,
			autoUpdateInput: true,
			timePicker24Hour : true,
			timePicker : true,
			timePickerSeconds:true,
			"locale": {
				format: 'YYYY-MM-DD HH:mm:ss',
				applyLabel: "应用",
				cancelLabel: "取消",
				resetLabel: "重置",
				daysOfWeek : [ '日', '一', '二', '三', '四', '五', '六' ],
				monthNames: ['一月', '二月', '三月', '四月', '五月', '六月',
					                  '七月', '八月', '九月', '十月', '十一月', '十二月'
					        ]
			}
		},
		function(start, end, label) {
			beginTimeTake = start;
			if(!this.startDate){
				this.element.val('');
			}else{
				this.element.val(this.startDate.format(this.locale.format));
			}
		});

	var addModalValidate = $("#addModal .form").validate({
		errorElement : 'span',
        errorClass : 'help-block',
        focusInvalid : true,
		rules : {
			OBJECT_NAME : {
				required : true,
				maxlength: 150
			},
			PROCEDURE_NAME : {
				required : true,
				maxlength: 33
			}
		},
		messages : {
			OBJECT_NAME : {
				required :"对象名称不能为空"
			},
			PROCEDURE_NAME : {
				required :"请输入过程名称"
			}
		},
		highlight : function(element) {
            $(element).closest('.form-group').addClass('has-error');
        },
        success : function(label) {
            label.closest('.form-group').removeClass('has-error');
            label.remove();
        },
        errorPlacement : function(error, element) {
            element.parent('div').append(error);
        },
        submitHandler : function(form) {
        	$.post(base_url + "/procedure/updateOne",  $("#addModal .form").serialize(), function(data, status) {
    			if (data.code == "200") {
					$('#addModal').modal('hide');
					layer.open({
						title: '系统提示',
						content: '新增任务成功',
						icon: '1',
						end: function(layero, index){
							jobTable.fnDraw();
							//window.location.reload();
						}
					});
    			} else {
					layer.open({
						title: '系统提示',
						content: (data.msg || "新增失败"),
						icon: '2'
					});
    			}
    		});
		}
	});
	$("#addModal").on('hide.bs.modal', function () {
		$("#addModal .form")[0].reset();
		addModalValidate.resetForm();
		$("#addModal .form .form-group").removeClass("has-error");
		$(".remote_panel").show();	// remote

		$("#addModal .form input[name='executorHandler']").removeAttr("readonly");
	});


	// 更新
	$("#procedure_list").on('click', '.update',function() {

        var id = $(this).parent('p').attr("id");
        var row = tableData['key'+id];
        if (!row) {
            layer.open({
                title: '系统提示',
                content: ("任务信息加载失败，请刷新页面"),
                icon: '2'
            });
            return;
        }

		// base data
		$("#updateModal .form input[name='OBJECT_ID']").val( row.OBJECT_ID );
		$("#updateModal .form input[name='OBJECT_NAME']").val( row.OBJECT_NAME );
		$("#updateModal .form input[name='OBJECT_DESC']").val( row.OBJECT_DESC );
		$("#updateModal .form input[name='PROCEDURE_NAME']").val( row.PROCEDURE_NAME );
		$("#updateModal .form select[name='ACTIVE']").val( row.ACTIVE );
		$("#updateModal .form input[name='INTERVAL']").val( row.INTERVAL );
		$("#updateModal .form input[name='START_TIME']").val( row.START_TIME );
		$("#updateModal .form input[name='MAX_INTERVAL']").val( row.MAX_INTERVAL );
		$("#updateModal .form input[name='ISRERUN']").val( row.ISRERUN );
		$("#updateModal .form select[name='IS_HISTORY']").val( row.IS_HISTORY );
		$("#updateModal .form input[name='HIS_RUN_FLAG']").val( row.HIS_RUN_FLAG );
		$("#updateModal .form input[name='RUN_FLAG']").val( row.RUN_FLAG );
		$("#updateModal .form input[name='RUNTIME']").val( row.RUNTIME );
		$("#updateModal .form input[name='HIS_START_TIME']").val( row.HIS_START_TIME );
		$("#updateModal .form input[name='HIS_END_TIME']").val( row.HIS_END_TIME );
		$("#updateModal .form input[name='HIS_RUN_TIME']").val( row.HIS_RUN_TIME );
		$("#updateModal .form input[name='MAX_PROCESS_DATE']").val( row.MAX_PROCESS_DATE );
		$("#updateModal .form input[name='WAIT_INTERVAL']").val( row.WAIT_INTERVAL );
		$("#updateModal .form input[name='MAX_COUNT']").val( row.MAX_COUNT );
		$("#updateModal .form select[name='LEVEL_SEQ']").val( row.LEVEL_SEQ );
		$("#updateModal .form input[name='CURRENT_COUNT']").val( row.CURRENT_COUNT );
		$("#updateModal .form input[name='ROWCOUNT']").val( row.ROWCOUNT );
		$("#updateModal .form input[name='TIME_CONSUMING']").val( row.TIME_CONSUMING );

		// show
		$('#updateModal').modal({backdrop: false, keyboard: false}).modal('show');
		//console.log(row)
	});
	var updateModalValidate = $("#updateModal .form").validate({
		errorElement : 'span',
        errorClass : 'help-block',
        focusInvalid : true,

		rules : {
			OBJECT_NAME : {
				required : true,
				maxlength: 150
			},
			PROCEDURE_NAME : {
				required : true,
				maxlength: 33
			}
		},
		messages : {
			OBJECT_NAME : {
				required :"对象名称不能为空"
			},
			PROCEDURE_NAME : {
				required :"请输入过程名称"
			}
		},
		highlight : function(element) {
            $(element).closest('.form-group').addClass('has-error');
        },
        success : function(label) {
            label.closest('.form-group').removeClass('has-error');
            label.remove();
        },
        errorPlacement : function(error, element) {
            element.parent('div').append(error);
        },
        submitHandler : function(form) {
			// post
    		$.post(base_url + "/procedure/updateOne", $("#updateModal .form").serialize(), function(data, status) {
    			if (data.code == "200") {
					$('#updateModal').modal('hide');
					layer.open({
						title: '系统提示',
						content: '更新成功',
						icon: '1',
						end: function(layero, index){
							//window.location.reload();
							jobTable.fnDraw();
						}
					});
    			} else {
					layer.open({
						title: '系统提示',
						content: (data.msg || "更新失败"),
						icon: '2'
					});
    			}
    		});
		}
	});
	$("#updateModal").on('hide.bs.modal', function () {
		$("#updateModal .form")[0].reset()
	});


	$(".rerun").click(function(){
		reRunModel.initTableName();
		reRunModel.onChange(logTable);
		$('#reRunModal').modal({backdrop: false, keyboard: false,width:'90%',height:'90%'}).modal('show');
	});

	$("#searchLogBtn").click(function(){
		reRunModel.onChange(logTable);
	})


	// 过滤时间
	$('#reRunModal').find('#reRunTime').daterangepicker({
		autoApply:true,
		singleDatePicker:false,
		showDropdowns:true,        // 是否显示年月选择条件
		timePicker: true, 			// 是否显示小时和分钟选择条件
		timePickerIncrement: 10, 	// 时间的增量，单位为分钟
		timePicker24Hour : true,
		opens : 'left', //日期选择框的弹出位置
		ranges: {
			'最近1小时': [moment().subtract(1, 'hours'), moment()],
			'今日': [moment().startOf('day'), moment().endOf('day')],
			'昨日': [moment().subtract(1, 'days').startOf('day'), moment().subtract(1, 'days').endOf('day')],
			'最近7日': [moment().subtract(6, 'days'), moment()],
			'最近30日': [moment().subtract(29, 'days'), moment()],
			'本月': [moment().startOf('month'), moment().endOf('month')],
			'上个月': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
		},
		locale : {
			format: 'YYYY-MM-DD HH:mm:ss',
			separator : ' - ',
			customRangeLabel : '自定义',
			applyLabel : '确定',
			cancelLabel : '取消',
			fromLabel : '起始时间',
			toLabel : '结束时间',
			daysOfWeek : [ '日', '一', '二', '三', '四', '五', '六' ],
			monthNames : [ '一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月' ],
			firstDay : 1,
			startDate: moment().startOf('day'),
			endDate: moment().endOf('day')
		}
	});

	$("#reRun-bt").click(function () {
		reRunModel.etlReRunExecute()
	});

	$("#all-reRun-bt").click(function () {
		reRunModel.etlReRunExecute("Y")
	});
});

var reRunModel = {
	initTableName:function(){
		$("#reRunModal").find("#TABLE_NAME").empty();
		$.post(base_url+"/procedure/etlReRunTableList",function(data){
			//console.log(data.data)
			if(data.data !=null){
				$(data.data).each(function(index,item){
					$("#reRunModal").find("#TABLE_NAME").append("<option value='"+item.TABLE_NAME+"'>"+item.TABLE_NAME+"</option>");
				});
			}
			$("#reRunModal").find("#TABLE_NAME").selectpicker("refresh");
		})
	},

	onChange:function(table){
		table.fnDraw()
	},

	initTable:function(){
		var rerunLogList = $("#rerun_log_list").dataTable({
			"deferRender": false,
			"processing" : false,
			"serverSide": true,
			'paging':false,
			"bAutoWidth": true,
			"ajax": {
				url: base_url + "/procedure/etlReRunList",
				type:"post",
				data : function ( d ) {
					var obj = {};
					var tableName = $("#TABLE_NAME").selectpicker("val");
					if(tableName != null){
						tableName = "'"+tableName.join("','")+"'"
					}else{
						tableName = ""
					}
					obj.TABLE_NAME = tableName;
					//obj.PROCEDURE_NAME = $('#PROCEDURE_NAME').val();
					//obj.IS_HISTORY = $('#IS_HISTORY').val();
					//obj.start = d.start ;
					//obj.length = d.length ;
					return obj;
				}
			},
			"searching": false,
			"ordering": false,
			//"scrollX": '120%',	// X轴滚动条，取消自适应
			//"scrollY": true,
			"columns": [
				{
					"data": 'TABLE_NAME',
					"visible" : true,
					"width":'20%'
				},
				{
					"data": 'PROCEDURE_NAME',
					"visible" : true,
					"width":'20%',
				},
				{

					"data": 'LEVEL_SEQ',
					"visible" : true,
					"width":'10%'
				},
				{

					"data": 'START_TIME',
					"width":'20%',
					"render": function ( data, type, row ) {
						return data?moment(new Date(data)).format("YYYY-MM-DD HH:mm:ss"):"";
					}
				},
				{

					"data": 'END_TIME',
					"visible" : true,
					"width":'10%',
					"render": function ( data, type, row ) {
						return data?moment(new Date(data)).format("YYYY-MM-DD HH:mm:ss"):"";
					}
				}
			],
			"language" : {
				"sProcessing" : "处理中...",
				"sLengthMenu" : "每页 _MENU_ 条记录",
				"sZeroRecords" : "没有匹配结果",
				"sInfo" : "第 _PAGE_ 页 ( 总共 _PAGES_ 页，_TOTAL_ 条记录 )",
				"sInfoEmpty" : "无记录",
				"sInfoFiltered" : "(由 _MAX_ 项结果过滤)",
				"sInfoPostFix" : "",
				"sSearch" : "搜索:",
				"sUrl" : "",
				"sEmptyTable" : "表中数据为空",
				"sLoadingRecords" : "载入中...",
				"sInfoThousands" : ",",
				"oPaginate" : {
					"sFirst" : "首页",
					"sPrevious" : "上页",
					"sNext" : "下页",
					"sLast" : "末页"
				},
				"oAria" : {
					"sSortAscending" : ": 以升序排列此列",
					"sSortDescending" : ": 以降序排列此列"
				}
			}
		});
		return rerunLogList;
	},

	etlReRunExecute:function(all) {
		var obj = {};
		var tableName = $("#TABLE_NAME").selectpicker("val");
		if (tableName != null) {
			tableName = "'" + tableName.join("','") + "'"
		} else if (all == "Y") {
			tableName = "Y"
		} else {
			layer.open({
				title: '系统提示',
				content: "请选择数据源表",
				icon: '2'
			});
			return
		}


		var reRunTime = $("#reRunTime").val();
		if (reRunTime == null || reRunTime == "") {
			layer.open({
				title: '系统提示',
				content: "请选择重跑时间",
				icon: '2'
			});
			return
		}

		var threadCount = $("#threadCount").val()
		if (threadCount == null || threadCount == "") {
			layer.open({
				title: '系统提示',
				content: "请输入进程数（数字）",
				icon: '2'
			});
			return
		}

		obj.TABLE_NAME = tableName;
		obj.THREAD_COUNT = threadCount;
		obj.reRunTime = reRunTime;

		var typeName = ""
		if(tableName=="Y"){
			typeName = "是否一键重跑"
		}else{
			typeName = "是否按设定执行"
		}

		layer.confirm('确认' + typeName + '?', {icon: 3, title:'系统提示'}, function(index){
			layer.close(index);
			$.post(base_url + "/procedure/etlReRunExecute", obj, function (data) {
				//console.log(data.code)
				if (data.code == "200") {
					$("#reRunModal").modal('hide');
					layer.open({
						title: '系统提示',
						content: data.msg,
						icon: '1'
					});
				} else {
					layer.open({
						title: '系统提示',
						content: data.msg,
						icon: '2'
					});
				}
			})
		});

	}

}

function logUrl(url) {
	//alert(  url)
	window.location.href = url
}